package com.future.lock.home.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Parcelable;

import com.future.baselib.entity.MessageEvent;
import com.future.baselib.utils.EventBusUtil;

/**
 * 监听网络链接变化广播
 * Created by jniu on 2017/11/23.
 */

public class NetworkConnectChangeReceiver extends BroadcastReceiver {

    public static final int WIFI_CONNECT = 10001;
    public static final int WIFI_DISCONNECT = 10002;


    @Override
    public void onReceive(Context context, Intent intent) {
        // 这个监听网络连接的设置，包括wifi和移动数据的打开和关闭。.
        // 最好用的还是这个监听。wifi如果打开，关闭，以及连接上可用的连接都会接到监听。见log
        // 这个广播的最大弊端是比上边两个广播的反应要慢，如果只是要监听wifi，我觉得还是用上边两个配合比较合适
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
            ConnectivityManager manager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo info = manager.getActiveNetworkInfo();
            if (info != null && info.isAvailable()) {
                int infoType = info.getType();
                if (infoType == ConnectivityManager.TYPE_WIFI) {
                    //wifi
                    EventBusUtil.sendEvent(new MessageEvent(WIFI_CONNECT));
                }else if (infoType == ConnectivityManager.TYPE_MOBILE){
                    //手机网络
                    EventBusUtil.sendEvent(new MessageEvent(WIFI_DISCONNECT));
                }
            }else{
                //网络不可用
                EventBusUtil.sendEvent(new MessageEvent(WIFI_DISCONNECT));
            }


        }
    }
}
